package com.shinhye.elephantsafe;

import com.shinhye.elephantsafe.db.dao.AddressDao;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Vibrator;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class NumberBelongActivity extends Activity {

	private TextView tv_belong;
	private EditText et_number;
	private Vibrator vibrator;
	private final long[] pattern = {200,1500};
	private final int repeat = -1;
	private Animation animation;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_numberbelong);
		
		vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
		et_number = (EditText) findViewById(R.id.et_number);
		tv_belong = (TextView) findViewById(R.id.tv_belong);
		animation = AnimationUtils.loadAnimation(NumberBelongActivity.this, R.anim.translate_editable_shock);
		
		et_number.addTextChangedListener(new TextWatcher() {
			//文本改变时，不可以对控件操作
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				if(s.length() >= 3) {
					String address = AddressDao.addressQuery(s.toString());
					tv_belong.setText(address == null ? "" : address);
				}
			}
			//文本改变前
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}
			//文本改变后，可以对该Editable控件进行操作
			@Override
			public void afterTextChanged(Editable s) {
			}
		});
		
		
	}
	
	public void querybelong(View v) {
		String number = et_number.getText().toString().trim();
		if(TextUtils.isEmpty(number)) {
			et_number.startAnimation(animation);
			vibrator.vibrate(pattern, repeat);
			Toast.makeText(this, "号码不能为空！", Toast.LENGTH_SHORT).show();
			return;
		}
		String address = AddressDao.addressQuery(number);
		if(TextUtils.isEmpty(address)) {
			et_number.startAnimation(animation);
			vibrator.vibrate(pattern, repeat);
			tv_belong.setText("查询不到结果！请确认号码是否输入正确！");
			tv_belong.setTextColor(Color.RED);
		} else {
			tv_belong.setText("查询结果：\n\n=>" + address);
			tv_belong.setTextColor(Color.BLACK);
		}
	}
	
}
